package com.joke.mydiary.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.joke.mydiary.MainActivity;
import com.joke.mydiary.R;
import com.joke.mydiary.pojo.Diary;
import com.joke.mydiary.service.BackupIntentService;
import com.joke.mydiary.utils.BitmapUtils;
import com.joke.mydiary.utils.ChectNetUtil;

import java.text.SimpleDateFormat;


public class ShowDiaryFragment extends Fragment implements View.OnClickListener {

    private ShowDiaryFragmentListener mListener;
    private TextView txtShowDate, txtShowContent;
    private ImageView imageView3;
    private Button btnShare, btnBackup, btnDelete;
    private Diary diary;
    private int touchCount = 0;
    private long startTime = 0l;


    public static ShowDiaryFragment getInstance(Bundle bundle) {
        ShowDiaryFragment sdf = new ShowDiaryFragment();
        sdf.setArguments(bundle);
        return sdf;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_show_diary, container, false);
        txtShowDate = (TextView) view.findViewById(R.id.txtShowDate);
        txtShowContent = (TextView) view.findViewById(R.id.txtShowContent);
        btnShare = (Button) view.findViewById(R.id.btnShare);
        btnBackup = (Button) view.findViewById(R.id.btnBackup);
        btnDelete = (Button) view.findViewById(R.id.btnDelete);


        diary = (Diary) this.getArguments().getSerializable("diary");

        txtShowDate.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(diary.getDate()));
        //当路劲不为null时去处理图片
        if (diary.getImagePath() != null && !"".equals(diary.getImagePath().trim())) {
            imageView3 = (ImageView) view.findViewById(R.id.imageView3);
            Bitmap bitmap =  BitmapUtils.decodeSimpledBitmapFromResourse(diary.getImagePath(), 400, 400);
            imageView3.setImageBitmap(bitmap);
            imageView3.setAdjustViewBounds(true);
        }
        txtShowContent.setText(diary.getContent());
        txtShowContent.setClickable(true);
        txtShowContent.setFocusable(true);

        //设置文本双击编辑
        txtShowContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    if (touchCount == 1) {
                        startTime = System.currentTimeMillis();
                    } else if (touchCount == 2) {
                        touchCount = 0;
                        if (System.currentTimeMillis() - startTime < 500) {
                            mListener.showUpdateFragment();
                        }
                    }
                    touchCount++;
                }
                return false;
            }
        });
        btnDelete.setOnClickListener(this);
        btnShare.setOnClickListener(this);
        btnBackup.setOnClickListener(this);
        return view;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (ShowDiaryFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnDelete:
                delete();
                break;
            case R.id.btnBackup:
                //首先检查网络是否可用
                boolean flag=new ChectNetUtil().isNetWorkConnected(getActivity());
                if(flag) {
                    //可用，启动服务，备份
                    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    boolean isOpend = sp.getBoolean("isOpend_preference", false);
                    if(isOpend) {
                        //获取云备份信息
                        TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                        String phone = tm.getLine1Number();
                        String username = sp.getString("username_preference", phone);
                        String uriPath = sp.getString("ip_preference", "127.0.0.1");

                        //备份
                        Intent backupIntent = new Intent(getActivity(), BackupIntentService.class);
                        backupIntent.putExtra("diary", diary);
                        backupIntent.putExtra("userName", username);
                        backupIntent.putExtra("uriPath",uriPath);
                        mListener.startBackupService(backupIntent);
                    }else
                    {
                        //没有打开云备份设置
                        Toast.makeText(getActivity(), "请在设置中打开云备份选项!", Toast.LENGTH_SHORT).show();
                    }
                }else
                {
                    //不可用，提示用户
                    Toast.makeText(getActivity(), "网络不可用，无法备份", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnShare:
                mListener.shareDiary(diary);
                break;
        }

    }


    public Diary getDiary() {
        return this.diary;
    }


    //删除时弹出确认对话框
    private void delete() {
        AlertDialog.Builder builder = new AlertDialog.Builder((Context) mListener);
        builder.setMessage("是否删除所选备忘录？");
        builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean flag = mListener.deleteDiary(diary.get_id());
                dialog.dismiss();
                if (flag) {
                    Intent intent = new Intent((Context) mListener, MainActivity.class);
                    startActivity(intent);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }


    public interface ShowDiaryFragmentListener {

        public boolean deleteDiary(int id);

        public void showUpdateFragment();

        public void shareDiary(Diary diary);

        public void startBackupService(Intent intent);


    }

}
